package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ApArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
@RequiredArgsConstructor
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    //文章mapper
    private final WmNewsMapper wmNewsMapper;

    //审核文本
    private final GreenTextScan greenTextScan;

    //审核图片
    private final GreenImageScan greenImageScan;

    //下载图片
    private final FileStorageService fileStorageService;

    //Article
    private final IArticleClient articleClient;

    //频道mapper
    private final WmChannelMapper wmChannelMapper;

    //用户mapper
    private final WmUserMapper wmUserMapper;

    //敏感词mapper
    private final WmSensitiveMapper wmSensitiveMapper;

    //图片识别文字
    private final Tess4jClient tess4jClient;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Async//表明当前方法是一个异步调用方法
    @Override
    public void autoScanWmNews(Integer id) {

        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            throw new RuntimeException("自媒体文章不存在");
        }

        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //从内容中提取纯文本内容和图片
            Map<String, Object> textAndImages = handleTextAndImages(wmNews);


            //2.审核文本内容  阿里云接口
      /*  boolean isTextScan = handleTextScan((String) textAndImages.get("content"), wmNews);
        if (!isTextScan){
            return;
        }*/

            //3.审核图片  阿里云接口
    /*    boolean isImagesScan = handleImagesScan((List<String>) textAndImages.get("images"), wmNews);
        if (!isImagesScan){
            return;
        }*/

            //4.自管理敏感词过滤
            boolean isSensitiveScan=handleSensitiveScan((String) textAndImages.get("content"), wmNews);
            if (!isSensitiveScan){
                return;
            }


            //4.审核成功 保存app端的相关文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            if (!responseResult.getCode().equals(200)){
                throw new RuntimeException("文章审核保存app端失败");
            }

            //回填article_id
            wmNews.setArticleId((Long) responseResult.getData());

            //将文章状态变为已发布

            wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());



            //拒绝理由
            wmNews.setReason("发布成功");

            wmNewsMapper.updateById(wmNews);
        }


    }

    /**
     * 自管理敏感词过滤
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {

        //定义审核变量
        boolean flage = true;

        //文章内容为空 直接返回通过
        if (content.length()==0) {
            return flage;
        }

        //获取所有的敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);

        //查看文章中是哦都包含敏感词
        Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(content);
        if (stringIntegerMap.size()>0) {

            //将状态变为审核失败
            wmNews.setStatus(WmNews.Status.FAIL.getCode());
            //拒绝理由
            wmNews.setReason("内容中含有敏感词信息"+ stringIntegerMap);

            wmNewsMapper.updateById(wmNews);

            //修改为false
            flage = false;
        }

        return flage;
    }

    /**
     * 保存app端相关文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        ApArticleDto apArticleDto = new ApArticleDto();

        //属性拷贝
        BeanUtils.copyProperties(wmNews,apArticleDto );

        //文章布局
        apArticleDto.setLayout(wmNews.getType());

        //频道名称
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            apArticleDto.setChannelName(wmChannel.getName());
        }

        //作者ID
        apArticleDto.setAuthorId(wmNews.getUserId().longValue());

        //作者名字
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            apArticleDto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if (wmNews.getArticleId()!=null){
            apArticleDto.setId(wmNews.getArticleId());
        }

        //设置创建时间
        apArticleDto.setCreatedTime(new Date());

        //保存文章
        ResponseResult responseResult = articleClient.saveArticle(apArticleDto);


        return responseResult;
    }

    /**
     * 审核图片内容
     *
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {

        //定义审核变量
        boolean flage = true;

        //文章内容为空 直接返回通过
        if (images.size() == 0 || images == null) {
            return flage;
        }

        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        //用集合装图片字节数组
        List<byte[]> imageList = new ArrayList<>();

        try {
            for (String image : images) {

                //下载图片 一次只能下载一张
                byte[] bytes = fileStorageService.downLoadFile(image);

                //byte[] 转换为bufferedImages
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                BufferedImage bufferedImage = ImageIO.read(bais);

                //提取图片文字
                String result = tess4jClient.doOCR(bufferedImage);

                //过滤文字
                boolean isSensitive = handleSensitiveScan(result, wmNews);
                if (!isSensitive) {
                    log.info("文字含有敏感信息 审核不通过");
                    return isSensitive;
                }

                imageList.add(bytes);
            }
        }catch (Exception e){
            e.printStackTrace();
        }



        //审核图片
        try {
            Map map = greenImageScan.imageScan(imageList);
            if (map != null) {
                //审核失败
                if (map.get("suggestion").equals("block")) {

                    flage = false;

                    //将状态变为审核失败
                    wmNews.setStatus(WmNews.Status.FAIL.getCode());
                    //拒绝理由
                    wmNews.setReason("图片中含有违规信息");

                    wmNewsMapper.updateById(wmNews);
                }

                //不确定信息
                if (map.get("suggestion").equals("review")) {

                    flage = false;

                    //转为人工审核
                    wmNews.setStatus((WmNews.Status.ADMIN_AUTH.getCode()));
                    //拒绝理由
                    wmNews.setReason("图片信息不确定 转为人工审核");

                    wmNewsMapper.updateById(wmNews);
                }

            }

        } catch (Exception e) {
            flage = false;
            throw new RuntimeException(e);
        }

        return flage;
    }


    /**
     * 审核纯文本内容
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {

        //定义审核变量
        boolean flage = true;

        //文章内容为空 直接返回通过
        if ((wmNews.getTitle() + content).length() == 0) {
            return flage;
        }

        try {

            //返回的map是审核的结果
            Map map = greenTextScan.greeTextScan(wmNews.getTitle() + content);
            if (map != null) {
                //审核失败
                if (map.get("suggestion").equals("block")) {

                    flage = false;

                    //将状态变为审核失败
                    wmNews.setStatus(WmNews.Status.FAIL.getCode());
                    //拒绝理由
                    wmNews.setReason("文章中含有违规信息");

                    wmNewsMapper.updateById(wmNews);
                }

                //不确定信息
                if (map.get("suggestion").equals("review")) {

                    flage = false;

                    //转为人工审核
                    wmNews.setStatus((WmNews.Status.ADMIN_AUTH.getCode()));
                    //拒绝理由
                    wmNews.setReason("文章信息不确定 转为人工审核");

                    wmNewsMapper.updateById(wmNews);
                }
            }
        } catch (Exception e) {

            flage = false;

            throw new RuntimeException(e);
        }


        return flage;
    }


    /**
     * 1.从自媒体文章中提取文本内容和图片
     * 2.提取文章的封面图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {

        //存储纯文本内容
        StringBuilder stringBuilder = new StringBuilder();

        //存储图片内容
        List<String> images = new ArrayList<>();

        //1.从自媒体文章的内容中提取文本和图片
        if (StringUtils.isNotBlank(wmNews.getContent())) {
            //将JSON数据转换为Map集合
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {

                //获取到文本
                if (map.get("type").equals("text")) {
                    stringBuilder.append(map.get("value"));
                }

                //获取到图片
                if (map.get("type").equals("image")) {
                    images.add(map.get("value").toString());
                }

            }
        }


        //2.提取文章的封面图片
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        Map<String, Object> textAndImages = new HashMap<>();

        textAndImages.put("content", stringBuilder.toString());
        textAndImages.put("images", images);

        return textAndImages;
    }
}





















